package db;

import java.awt.Component;
import java.awt.EventQueue;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;




import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class DBInput {
	public ResultSet resultSet = null;
	public ResultSet rs;
	private JFrame frame;
	private final JScrollPane scrollPane = new JScrollPane();
	private JTable table;
	String tab;
	DBconnector core;
	TableColumn col ;
	Vector<String> names;
	Vector<String> key;
	Vector<String> type;
	/**
	 * Launch the application.
	 */
	

	/**
	 * Create the application.
	 */
	public DBInput(Vector v,DBconnector core,String tab) {
		initialize();
		DefaultTableModel model;
		this.tab=tab;
		this.core=core;
		this.frame.setVisible(true);
		int rows=v.size();
		names=new Vector();
		type=new Vector();
		key=new Vector();
		model= (DefaultTableModel) table.getModel();
		try {
			resultSet=core.statement.executeQuery("describe "+tab);
			resultSet.next();
			while(resultSet.next()){
				names.add(resultSet.getString(1));
				key.add(resultSet.getString(4));
				type.add(resultSet.getString(2));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(new JFrame(), e.getLocalizedMessage());
		}
		model.addRow(new Vector());
		for(int i=0;i<rows;i++){
			model.addColumn(v.get(i).toString());
			}
		for(int i=0;i<rows;i++){
		
				if(key.get(i).contains("MUL")){
					addcb(i);
				
			} 
		}

		
		
	}
	public void addcb(int i){
		ResultSet LinkedNames;
		Vector<String> temp=new Vector();
		String linkedTab;
			try {
				LinkedNames= core.statement.executeQuery("select REFERENCED_TABLE_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_SCHEMA='muzyka' and Table_name='"+tab+"' and COLUMN_NAME='"+names.get(i)+"' and referenced_table_name is not null;");
				LinkedNames.next();
				linkedTab=LinkedNames.getString(1);
				LinkedNames= core.statement.executeQuery("Select * From "+linkedTab);
			
				while(LinkedNames.next()){
					temp.add(LinkedNames.getString(2));
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				JOptionPane.showMessageDialog(new JFrame(), e.getLocalizedMessage());
			}
		
		String[] values = temp.toArray(new String[0]);
	    col = table.getColumnModel().getColumn(i);
	    col.setCellEditor(new MyComboBoxEditor(values));
	    col.setCellRenderer(new MyComboBoxRenderer(values));
	}
	public int getReferencedTableID(String column,String value){
		try {
			System.out.println(column+" "+value);
			rs=core.statement.executeQuery("select REFERENCED_TABLE_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_SCHEMA='muzyka' and Table_name='"+tab+"' and COLUMN_NAME='"+column+"' and referenced_table_name is not null;");
			rs.next();
			String linkedTab =rs.getString(1);
			System.out.println(linkedTab);
			rs=core.statement.executeQuery("Select * from "+linkedTab);
			rs.next();
			rs=core.statement.executeQuery("Select * From "+linkedTab+" Where "+rs.getMetaData().getColumnName(2)+" Like '"+value+"'");
			rs.next();
			return Integer.parseInt(rs.getString(1));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0;
		}
	    
		
	}
	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				frame.setVisible(false);
			}
		});
		frame.setBounds(100, 100, 478, 151);
		frame.getContentPane().setLayout(null);
		scrollPane.setBounds(0, 0, 462, 68);
		frame.getContentPane().add(scrollPane);
		
		table = new JTable();
		table.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
			}
		) {
			
		});
		table.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
		scrollPane.setViewportView(table);
		

		
		
		JButton btnNewButton = new JButton("Insert");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (table.isEditing()) {
	                table.getCellEditor().stopCellEditing();
	            }
				
				String s=tab;
				
				
					if(type.get(0).contains("int")){
						
						if(key.get(0).contains("MUL")){
						MyComboBoxRenderer temp =(MyComboBoxRenderer) table.getCellRenderer(0, 0);
						if(temp.getSelectedItem()!=null)
							s+="(" +(getReferencedTableID(names.get(0),temp.getSelectedItem().toString()));
						else
						{
							frame.dispose();
							return;
						}
							
						
						}
						else{
							s+="(" +table.getModel().getValueAt(0 , 0);
						}
					}	
					else
						if(key.get(0).contains("MUL")){
							MyComboBoxRenderer temp =(MyComboBoxRenderer) table.getCellRenderer(0, 0);
							if(temp.getSelectedItem()!=null)
							s+="('" +(getReferencedTableID(names.get(0),temp.getSelectedItem().toString()))+"'";
							else
							{
								frame.dispose();
								return;
							}
							}
							else{
								s+="('" +table.getModel().getValueAt(0 , 0)+"'";
							}
				
				for(int i=1;i<table.getColumnCount();i++ ){
					
						if(type.get(i).contains("int")){
							if(key.get(i).contains("MUL")){
								
								MyComboBoxRenderer temp =(MyComboBoxRenderer) table.getCellRenderer(0, i);
								if(temp.getSelectedItem()!=null)
								s+=", "+(getReferencedTableID(names.get(i),temp.getSelectedItem().toString()));
								else
								{
									frame.dispose();
									return;
								}
								}
								else{
									s+=", "+table.getModel().getValueAt(0, i);
								}
						
						}
						else
							if(key.get(i).contains("MUL")){
								MyComboBoxRenderer temp =(MyComboBoxRenderer) table.getCellRenderer(0, i);

								if(temp.getSelectedItem()!=null)
								s+=", '"+(getReferencedTableID(names.get(i),temp.getSelectedItem().toString()))+"'";
								else
								{
									frame.dispose();
									return;
								}
								}
								else{
									s+=", '"+table.getModel().getValueAt(0, i)+"'";
								}
				}
				s+=");";
				core.insert(s);
				frame.setVisible(false);
			}
		});
		btnNewButton.setBounds(10, 79, 89, 23);
		frame.getContentPane().add(btnNewButton);
		
		JButton btnBack = new JButton("Back");
		btnBack.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				frame.dispose();
			}
		});
		btnBack.setBounds(109, 79, 89, 23);
		frame.getContentPane().add(btnBack);
	}
}

class MyComboBoxRenderer extends JComboBox implements TableCellRenderer {
	  public MyComboBoxRenderer(String[] items) {
	    super(items);
	
	  }

	  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
	      boolean hasFocus, int row, int column) {
	    if (isSelected) {
	      setForeground(table.getSelectionForeground());
	      super.setBackground(table.getSelectionBackground());
	    } else {
	      setForeground(table.getForeground());
	      setBackground(table.getBackground());
	    }
	    setSelectedItem(value);
	    return this;
	  }
	}

class MyComboBoxEditor extends DefaultCellEditor {
	  public MyComboBoxEditor(String[] items) {
	    super(new JComboBox(items));
	  }
	}
